package com.retail.bbq.cola.config;

import com.retail.bbq.cola.annotation.DecryptResponse;
import com.retail.bbq.cola.annotation.EncryptResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;

import javax.annotation.PostConstruct;


@Configuration
@Slf4j
public class NeedCryptoConfig {

    @Value("${encrypt.flag}")
    private Boolean ymlEncryptFlag;

    private static Boolean encryptFlag = false;

    @PostConstruct
    public void NeedCryptoConfig(){
        encryptFlag =  ymlEncryptFlag;
    }

    public boolean isNeedEncrypt(MethodParameter returnType) {
        boolean encrypt = false;
        log.info("获取加解密的配置:{}", encryptFlag);
        if(encryptFlag){
            boolean classPresentAnno = returnType.getContainingClass().isAnnotationPresent(EncryptResponse.class);
            boolean methodPresentAnno = returnType.getMethod().isAnnotationPresent(EncryptResponse.class);
            if(classPresentAnno){
                //类上有加加密注解,则全部方法都要加密
                boolean classEncrypt = returnType.getContainingClass().getAnnotation(EncryptResponse.class).value();
                if(classEncrypt){
                    return true;
                }
            }
            if(methodPresentAnno){
                //方法上有加加密注解,则方法要加密
                boolean methodEncrypt = returnType.getMethod().getAnnotation(EncryptResponse.class).value();
                return methodEncrypt;
            }
        }
        return encrypt;
    }

    public boolean isNeedDecrypt(MethodParameter returnType) {
        boolean encrypt = false;
        if(encryptFlag){
            boolean classPresentAnno = returnType.getContainingClass().isAnnotationPresent(DecryptResponse.class);
            boolean methodPresentAnno = returnType.getMethod().isAnnotationPresent(DecryptResponse.class);
            if(classPresentAnno){
                //类上有加加密注解,则全部方法都要加密
                boolean classEncrypt = returnType.getContainingClass().getAnnotation(DecryptResponse.class).value();
                if(classEncrypt){
                    return true;
                }
            }
            if(methodPresentAnno){
                //方法上有加加密注解,则方法要加密
                boolean methodEncrypt = returnType.getMethod().getAnnotation(DecryptResponse.class).value();
                return methodEncrypt;
            }
        }
        return encrypt;
    }
}
